import React, { Component } from 'react'
import { StyleSheet, Text, View, Dimensions, PixelRatio, Image, TouchableOpacity } from 'react-native'
import ImagePicker from 'react-native-image-picker'

const styles = StyleSheet.create({
  avatarContainer: {
    borderColor: '#9B9B9B',
    borderWidth: 1 / PixelRatio.get(),
    justifyContent: 'center',
    alignItems: 'center'
  },
  avatar: {
    borderRadius: 75,
    width: 100,
    height: 100
  }
});

class ImagePickers extends Component {
  state = {
    avatarSource: null
  }

  selectPhotoTapped() {
    const options = {
      quality: 1.0,
      maxWidth: 500,
      maxHeight: 500,
      storageOptions: {
        skipBackup: true
      }
    };
    ImagePicker.showImagePicker(options, (response) => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled photo picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        // const source = { uri: response.uri };
        const { addChange } = this.props
        // You can also display the image using data:
        const source = { uri: `data:image/jpeg;base64,${response.data}` };
        addChange({
          ...response,
          ...source
        })
        console.log('test upload', { ...response, ...source })
        this.setState({
          avatarSource: source
        });
      }
    });
  }
  render() {
    return (
      <View>
        <TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
          <View style={[styles.avatar, styles.avatarContainer, { marginBottom: 20 }]}>
            { this.state.avatarSource === null ? <Text>选择一张图片</Text> :
            <Image style={styles.avatar} source={this.state.avatarSource} />
            }
          </View>
        </TouchableOpacity>
      </View>
    )
  }
}

export default ImagePickers
